package com.translate.web.service.impl;

import com.translate.web.constant.RedisConstant;
import com.translate.web.dao.TeamMapper;
import com.translate.web.param.contract.IIdAndUserIdParam;
import com.translate.web.param.contract.ITeamSearchParam;
import com.common.util.StringUtil;
import com.translate.entity.Team;
import com.translate.vo.contract.ITeamVO;
import com.translate.web.service.ITeamService;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class TeamServiceImpl extends BaseTranslateServiceImpl<Team> implements ITeamService {
	public TeamServiceImpl(TeamMapper mapper) {
		super(mapper);
	}

	protected void insertPropteris(Team data) {
		long time = System.currentTimeMillis() / 1000;
		data.setCreateTime(time);
		data.setStatus((byte) 0);
		data.setDiscount(BigDecimal.valueOf(100));
		data.setCurrency(BigDecimal.ZERO);
		data.setUpdateTime(time);
	}

	protected void updatePropteris(Team data) {
		data.setUpdateTime(System.currentTimeMillis() / 1000);
	}

	protected Class<Team> getEntityClass() {
		return Team.class;
	}

	@Resource
	public void setRedisTemplate(RedisTemplate<String, ? extends Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	public <VO extends ITeamVO> List<VO> getTeamBySearch(ITeamSearchParam param, Class<VO> target) {

		TeamMapper teamMapper = this.getBaseMapper();

		String key = param.getKey();

		boolean isString = true;

		if (StringUtil.isNumber(key)) {
			isString = false;
		}

		List<Team> teamBySearch = teamMapper.getTeamBySearch(key, isString);

		return entityConvertToVo(teamBySearch, target);
	}

	@Override
	protected Team getEntityInstance() {
		// TODO Auto-generated method stub
		return new Team();
	}

	@Override
	public int deleteByUserId(int userId) {

		TeamMapper teamMapper = this.getBaseMapper();

		return teamMapper.deleteByUserId(userId);
	}

	@Override
	public Team getTeamFromCache(int id, long userId) {

		String teamKey = RedisConstant.getTeamKey(id, userId);

		ValueOperations<String, Team> opsForValue = (ValueOperations<String, Team>) this.redisTemplate.opsForValue();

		Team object = (Team) opsForValue.get(teamKey);

		if (null != object) {
			return object;
		}

		object = this.mapper.getDataByIdAndUserId(id, (int) userId);

		if (null == object) {

			object = new Team();

			opsForValue.set(teamKey, object, 2, TimeUnit.SECONDS);

			return object;
		}

		opsForValue.set(teamKey, object, 5, TimeUnit.SECONDS);

		return object;
	}

	@Override
	public int updateTeamDiscount(int id, long userId, Float discount) {
		// TODO Auto-generated method stub
		return 0;
	}

}